package com.hx.controller;

import com.hx.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
@Slf4j
@CrossOrigin(origins = {"http://localhost:81"})   //写访问我接口的应用的URL
public class OriginController {
    @RequestMapping("/test/origin")
    public Map<String, Object> testOrigin  (User user , HttpSession session, HttpServletResponse response) {
        log.info("user:{}",user);
        Map<String, Object>resultMap=new HashMap<>();

        if (!Objects.isNull(user) &&   !StringUtils.isEmpty(user.getName())){
            resultMap.put("success",true);
            resultMap.put("massage","收到了");
            resultMap.put("data",user);
        }else {

            resultMap.put("success", false);
            resultMap.put("message", "用户数据未接收");
            resultMap.put("data", null);
        }

        session.setAttribute("msg", "测试session");
        //一旦允许跨域携带cookie，那么需要在目标接口这边为其增加一个响应头，以供正常响应
        response.setHeader("Access-Control-Allow-Credentials", "true");

        return resultMap;
    }


    @GetMapping("/get/session")
    public String sessionGet(HttpSession session){
        String msg = (String) session.getAttribute("msg");
        System.out.println("msg = " + msg);
        return msg;
    }
        }



